package com.czkt.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

//@WebFilter(filterName = "AutoFilter",urlPatterns = "/*")
public class AutoFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        System.out.println("进入了过滤器");

        HttpServletRequest request = (HttpServletRequest) req;

        HttpServletResponse response = (HttpServletResponse) resp;

        HttpSession session = request.getSession();
        Set<String> filterUrl=new HashSet<>();
//        filterUrl.add("/403");
        filterUrl.add("/");
        filterUrl.add("/doLogin");
        filterUrl.add("/logout");

        System.out.println( request.getRequestURI());
        System.out.println( request.getRequestURL());
        if(session.getAttribute("loginUser")!=null || filterUrl.contains(request.getServletPath())
                || request.getServletPath().endsWith(".css")  || request.getServletPath().endsWith(".ico")

        ){
            chain.doFilter(req, resp);
        }else{
            response.sendRedirect("/");
        }


    }

    public void init(FilterConfig config) throws ServletException {

    }

}
